package com.team9.fitness.controller;

import com.team9.fitness.entity.ExerciseRecord;
import com.team9.fitness.service.ZRDDSSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 运动记录管理控制器
 */
@RestController
@RequestMapping("/api/exercise-records")
@Slf4j
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
public class ExerciseRecordController {

    @Autowired
    private ZRDDSSendService zrddsSendService;

    /**
     * 开始运动
     */
    @PostMapping("/start")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> startExercise(
            @RequestBody ExerciseRecord exerciseRecord) {
        
        log.info("开始运动请求: userId={}, exerciseId={}", exerciseRecord.getUserId(), exerciseRecord.getExerciseId());
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("userId", exerciseRecord.getUserId());
        requestBody.put("exerciseId", exerciseRecord.getExerciseId());
        requestBody.put("startTime", exerciseRecord.getStartTime());
        
        return zrddsSendService.sendBusinessRequest("EXERCISE_START", "POST", "/api/exercise-records/start", 
                exerciseRecord.getUserId().toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "运动开始成功");
                        result.put("data", response.getData());
                        log.info("运动开始成功: userId={}, exerciseId={}", exerciseRecord.getUserId(), exerciseRecord.getExerciseId());
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "运动开始失败");
                        log.warn("运动开始失败: userId={}, exerciseId={}, error={}", exerciseRecord.getUserId(), exerciseRecord.getExerciseId(), response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("运动开始异常: userId={}, exerciseId={}", exerciseRecord.getUserId(), exerciseRecord.getExerciseId(), throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "运动开始服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 结束运动
     */
    @PostMapping("/{recordId}/end")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> endExercise(
            @PathVariable Long recordId, @RequestBody Map<String, Object> endData) {
        
        log.info("结束运动请求: recordId={}", recordId);
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("recordId", recordId);
        requestBody.put("avgHeartRate", endData.get("avgHeartRate"));
        requestBody.put("maxHeartRate", endData.get("maxHeartRate"));
        requestBody.put("avgSpeed", endData.get("avgSpeed"));
        requestBody.put("maxSpeed", endData.get("maxSpeed"));
        
        return zrddsSendService.sendBusinessRequest("EXERCISE_END", "POST", "/api/exercise-records/" + recordId + "/end", 
                recordId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "运动结束成功");
                        result.put("data", response.getData());
                        log.info("运动结束成功: recordId={}", recordId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "运动结束失败");
                        log.warn("运动结束失败: recordId={}, error={}", recordId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("运动结束异常: recordId={}", recordId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "运动结束服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户的所有运动记录
     */
    @GetMapping("/user/{userId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getExerciseRecordsByUserId(@PathVariable Long userId) {
        
        log.info("获取用户运动记录请求: userId={}", userId);
        
        return zrddsSendService.sendBusinessRequest("EXERCISE_GET_BY_USER", "GET", "/api/exercise-records/user/" + userId, 
                userId.toString(), new HashMap<>())
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取运动记录成功");
                        result.put("data", response.getData());
                        log.info("获取运动记录成功: userId={}", userId);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取运动记录失败");
                        log.warn("获取运动记录失败: userId={}, error={}", userId, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取运动记录异常: userId={}", userId, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取运动记录服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 获取用户指定状态的运动记录
     */
    @GetMapping("/user/{userId}/status/{status}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getExerciseRecordsByUserIdAndStatus(
            @PathVariable Long userId, @PathVariable String status) {
        
        log.info("获取用户指定状态运动记录请求: userId={}, status={}", userId, status);
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("status", status);
        
        return zrddsSendService.sendBusinessRequest("EXERCISE_GET_BY_USER_STATUS", "GET", "/api/exercise-records/user/" + userId + "/status/" + status, 
                userId.toString(), requestBody)
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取运动记录成功");
                        result.put("data", response.getData());
                        log.info("获取运动记录成功: userId={}, status={}", userId, status);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取运动记录失败");
                        log.warn("获取运动记录失败: userId={}, status={}, error={}", userId, status, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取运动记录异常: userId={}, status={}", userId, status, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取运动记录服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }

    /**
     * 根据ID获取运动记录
     */
    @GetMapping("/{id}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getExerciseRecordById(@PathVariable Long id) {
        
        log.info("根据ID获取运动记录请求: id={}", id);
        
        return zrddsSendService.sendBusinessRequest("EXERCISE_GET_BY_ID", "GET", "/api/exercise-records/" + id, 
                id.toString(), new HashMap<>())
                .thenApply(response -> {
                    Map<String, Object> result = new HashMap<>();
                    if (response.getSuccess()) {
                        result.put("success", true);
                        result.put("message", "获取运动记录成功");
                        result.put("data", response.getData());
                        log.info("获取运动记录成功: id={}", id);
                    } else {
                        result.put("success", false);
                        result.put("message", response.getMessage() != null ? response.getMessage() : "获取运动记录失败");
                        log.warn("获取运动记录失败: id={}, error={}", id, response.getError());
                    }
                    return ResponseEntity.ok(result);
                })
                .exceptionally(throwable -> {
                    log.error("获取运动记录异常: id={}", id, throwable);
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", false);
                    result.put("message", "获取运动记录服务异常，请稍后重试");
                    return ResponseEntity.ok(result);
                });
    }
}
